﻿/*  
 *  IIS LogFile Analyser, Copyright (C) 2013. http://www.iis-analyser.com
 *  --
 *  This program is free software, provided "AS IS" WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
 * 
 *  File Author: Ian Quigley,    2013-02-23
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataStore;
using System.Configuration;
using System.IO;
using System.Text;
using System.Diagnostics;
using AppLogic;
using System.Web.Services;

namespace Web
{
    public partial class Files : BasePage
    {
        public long SiteId { get { return QueryParamLong( "siteId" ); } }

        private SiteRecord _site;
        public SiteRecord Site { get { return _site ?? (_site = Data.SiteById( SiteId )); } }

        [WebMethod]
        public static AjaxResponse Update( int siteId, string filePath )
        {
            if (Visitor.Current.IsAnonymous)
                return AjaxResponse.DenyAnonymous();

            if (siteId == 0 || string.IsNullOrWhiteSpace( filePath ))
                return AjaxResponse.Fail( "Missing siteId or filePath" );

            filePath = HttpUtility.UrlDecode( filePath );

            // process the file
            var store = GetDataStore();
            var site = store.SiteById(siteId);
            Processor proc = new Processor( store, site );
            proc.AddUpdateFile(  filePath );

            // rebuild the row for the view
            StringBuilder html = new StringBuilder();
            FileTableRow( store, site, html, filePath, true );

            return AjaxResponse.Ok( html.ToString() );
        }

        protected void Page_Load( object sender, EventArgs e )
        {
            if (Site == null)
                Response.Redirect( "sites.aspx" );

            if (!string.IsNullOrWhiteSpace( Request.QueryString["update"] ))
            {
                string filepath = HttpUtility.UrlDecode( Request.QueryString["update"] );

                Processor proc = new Processor( Data, Site );
                proc.AddUpdateFile( filepath );
                
            }

            UpdateDisplay();
        }

        private void UpdateDisplay()
        {            
            StringBuilder html = new StringBuilder();
            List<FileRecord> files = Site.Files.ToList();

            html.AppendFormat( "<h3>{0} files</h3>", Site.Name );
            html.AppendFormat("<a href='#' onclick='LogView.Admin.UpdateAllFiles({0});'>Add all files</a><br/>", Site.Id );
            html.AppendFormat( "<table cellspacing=0><thead><td>File</td><td>Action</td></thead>" );
            foreach (string fileName in Directory.GetFiles( Site.Folder, "*.log" ))
            {
                html.AppendFormat( "<tr data-filepath='{0}' >", HttpUtility.UrlEncode(fileName) );

                FileTableRow( Data, Site, html, fileName, 
                    (files.Exists( fr => string.Equals( fr.FilePath, fileName, StringComparison.OrdinalIgnoreCase ) )) );
                
                html.Append( "</tr>" );
            }
            html.Append( "</table>" );

            litOne.Text = html.ToString();
        }

        private static void FileTableRow(Store data, SiteRecord site, StringBuilder html, string filePath, bool isIndexed)
        {
            FileInfo info = new FileInfo( filePath );

            if (isIndexed)
            {
                var file = data.FindOrCreateFile( site, filePath );
                isIndexed = (file.SizeBytes == info.Length && file.Updated == info.LastWriteTimeUtc);
            }

            if (!isIndexed)
                html.AppendFormat( "<td data-action='update'>{0}</td><td><a href=\"#\" onclick=\"LogView.Admin.UpdateFile({1}, '{2}')\">update</a></td>", filePath, site.Id, HttpUtility.UrlEncode( filePath ) );
            else
                html.AppendFormat( "<td>{0}</td><td></td>", filePath);
        }

    }
}